<template>
  <div class="dept-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchText"
        placeholder="输入部门名称搜索"
        clearable
        @clear="handleSearchClear"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch" />
        </template>
      </el-input>
      <el-button type="primary" :icon="Plus" @click="handleAddRoot">新增根部门</el-button>
    </div>

    <!-- 部门树 -->
    <div class="tree-container">
      <el-tree
        ref="treeRef"
        node-key="id"
        :data="deptTree"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        highlight-current
        default-expand-all
      >
        <template #default="{ node, data }">
          <span class="custom-node">
            <span>{{ node.label }}</span>
            <span class="node-actions">
              <el-tooltip content="添加子部门" placement="top">
                <el-button
                  :icon="Plus"
                  size="small"
                  link
                  @click.stop="handleAddChild(data)"
                />
              </el-tooltip>
              <el-tooltip content="编辑" placement="top">
                <el-button
                  :icon="Edit"
                  size="small"
                  link
                  @click.stop="handleEdit(data)"
                />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  :icon="Delete"
                  size="small"
                  link
                  @click.stop="handleDelete(data)"
                />
              </el-tooltip>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @closed="handleDialogClosed"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getDeptTree, addDept, updateDept, deleteDept } from '@/api/dept'

// 树形数据
const deptTree = ref([])
const treeRef = ref()
const searchText = ref('')

// 弹窗控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const formData = ref({
  id: null,
  parentId: null,
  name: '',
  code: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }]
}

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 初始化部门树
const loadDeptTree = async () => {
  try {
    const res = await getDeptTree()
    deptTree.value = res.data
  } catch (error) {
    ElMessage.error('获取部门树失败')
  }
}

// 搜索部门
const handleSearch = () => {
  treeRef.value.filter(searchText.value)
}

// 清空搜索
const handleSearchClear = () => {
  searchText.value = ''
  treeRef.value.filter('')
}

// 树节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 新增根部门
const handleAddRoot = () => {
  formData.value = {
    id: null,
    parentId: 0, // 0表示根部门
    name: '',
    code: '',
    sort: 0,
    status: 1
  }
  dialogTitle.value = '新增根部门'
  dialogVisible.value = true
}

// 新增子部门
const handleAddChild = (data) => {
  formData.value = {
    id: null,
    parentId: data.id,
    name: '',
    code: '',
    sort: 0,
    status: 1
  }
  dialogTitle.value = `新增子部门（上级：${data.name}）`
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (data) => {
  formData.value = { ...data }
  dialogTitle.value = '编辑部门'
  dialogVisible.value = true
}

// 删除部门
const handleDelete = async (data) => {
  try {
    await ElMessageBox.confirm(
      `确认删除【${data.name}】部门吗？删除后不可恢复！`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteDept(data.id)
    ElMessage.success('删除成功')
    loadDeptTree()
  } catch (error) {
    console.log('取消删除', error)
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  try {
    if (formData.value.id) {
      await updateDept(formData.value)
      ElMessage.success('更新成功')
    } else {
      await addDept(formData.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    loadDeptTree()
  } catch (error) {
    console.log('操作失败', error)
  }
}

// 弹窗关闭重置
const handleDialogClosed = () => {
  formRef.value.resetFields()
}

// 初始化加载
onMounted(() => {
  loadDeptTree()
})
</script>

<style scoped>
.dept-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  width: 300px;
}

.tree-container {
  min-height: 500px;
}

.custom-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.node-actions {
  visibility: hidden;
}

:deep(.el-tree-node__content:hover) .node-actions {
  visibility: visible;
}
</style>